#include "book_dispose.h"

// 创建图书信息表的SQL语句
char *create_book_table = "create table if not exists bookinfo( "
                            "ID integer primary key autoincrement, " // 主键，自增ID
                            "name text not null, "                   // 书名，不能为空
                            "author text not null, "                 // 作者，不能为空
                            "publishing_house text not null, "       // 出版社，不能为空
                            "price real not null check(price >= 0), "// 价格，不能为空且必须大于等于0
                            "number integer not null check(number >= 1), "// 数量，不能为空且必须大于等于1
                            "borrowing_status integer default 1);"; // 借阅状态，默认为1（可借）

// 初始化数据表
int init_book_table()
{
    // 打开数据库文件book.db，db为全局变量
    int rc = sqlite3_open("book.db", &db);
    if(rc != SQLITE_OK)
    {
        perror("sqlite3_open"); // 打开失败打印错误
        exit(-1);
    }
    // 执行创建表的SQL语句
    rc = sqlite3_exec(db, create_book_table, NULL, 0, NULL);
    if(rc != SQLITE_OK)
    {
        perror("sqlite3_exec"); // 执行失败打印错误
        sqlite3_close(db);
        exit(-1);
    }
    sqlite3_close(db); // 关闭数据库
}

// 打印每行信息的回调函数
int print_callback(void *data, int argc, char **argv, char **colName)
{
    for(int i = 0; i < argc; i++)
    {
        printf("%s = %s\t", colName[i], argv[i]); // 打印列名和值
    }
    printf("\n");
    return 0;
}

// 按书名查询
int inquire_by_bookname(const char *bookname)
{
    int rc = sqlite3_open("book.db", &db); // 打开数据库
    if(rc != SQLITE_OK)
    {
        perror("sqlite3_open");
        exit(-1);
    }
    char sql[LEN];
    // 构造SQL语句，按书名查询
    snprintf(sql, LEN, "select * from bookinfo where name = '%s';", bookname);
    // 执行SQL语句，结果通过回调函数打印
    rc = sqlite3_exec(db, sql, print_callback, 0, NULL);
    if (rc != SQLITE_OK)
    {
        perror("sqlite3_exec");
        sqlite3_close(db);
        exit(-1);
    }
    sqlite3_close(db); // 关闭数据库
    return 0;
}

// 按作者查询
int inquire_by_author(const char *author)
{
    int rc = sqlite3_open("book.db", &db); // 打开数据库
    if(rc != SQLITE_OK)
    {
        perror("sqlite3_open");
        exit(-1);
    }
    char sql[LEN];
    // 构造SQL语句，按作者查询
    snprintf(sql, LEN, "select * from bookinfo where author = '%s';", author);
    // 执行SQL语句，结果通过回调函数打印
    rc = sqlite3_exec(db, sql, print_callback, 0, NULL);
    if (rc != SQLITE_OK)
    {
        perror("sqlite3_exec");
        sqlite3_close(db);
        exit(-1);
    }
    sqlite3_close(db); // 关闭数据库
    return 0;
}

// 按ID查询
int inquire_by_ID(const int id)
{
    int rc = sqlite3_open("book.db", &db); // 打开数据库
    if(rc != SQLITE_OK)
    {
        perror("sqlite3_open");
        exit(-1);
    }
    char sql[LEN];
    // 构造SQL语句，按ID查询
    snprintf(sql, LEN, "select * from bookinfo where ID = %d;", id);
    // 执行SQL语句，结果通过回调函数打印
    rc = sqlite3_exec(db, sql, print_callback, 0, NULL);
    if (rc != SQLITE_OK)
    {
        perror("sqlite3_exec");
        sqlite3_close(db);
        exit(-1);
    }
    sqlite3_close(db); // 关闭数据库
    return 0; 
}

// 保存图书信息到数据库
int save_bookdata()
{
    char bookname[LEN] = {0}, author[LEN] = {0}, publishing_house[LEN] = {0};
    double price = 0.0;
    int number = 0;
    if(sqlite3_open("book.db", &db) != SQLITE_OK)
    {
        perror("sqlite3_open");
        exit(-1);
    }
    printf("请输入图书名称：");
    fgets(bookname, LEN, stdin);
    bookname[strcspn(bookname, "\n")] = 0;
    printf("请输入作者名称：");
    fgets(author, LEN, stdin);
    author[strcspn(author, "\n")] = 0;
    printf("请输入出版社名称：");
    fgets(publishing_house, LEN, stdin);
    publishing_house[strcspn(publishing_house, "\n")] = 0;
    printf("请输入图书价格：");
    scanf("%lf", &price);
    printf("请输入图书数量：");
    scanf("%d", &number);
    fflush(stdin);
    char sql[1024] = { 0 };
    // 构造插入语句，将图书信息插入bookdata表
    sprintf(sql, "insert into bookinfo(name, author, publishing_house, price, number) values(\"%s\", \"%s\", \"%s\", %f, %d);",
        bookname, author, publishing_house, price, number);

    char* errmsg = 0;
    // 执行插入操作
    int rc = sqlite3_exec(db, sql, NULL, 0, &errmsg);
    if (rc != SQLITE_OK)
    {
        printf("insert error: %s\n", errmsg); // 插入失败打印错误信息
        sqlite3_free(errmsg);
        return -1;
    }
    printf("添加图书成功\n"); // 插入成功
    sqlite3_close(db);
    return 0;
}

// 删除指定ID的图书信息
int delete_bookdata(const int id)
{
    if(sqlite3_open("book.db", &db) != SQLITE_OK)
    {
        perror("sqlite3_open");
        exit(-1);
    }
    char sql[1024] = { 0 };
    // 构造删除语句，按id删除
    sprintf(sql, "delete from bookinfo where id = %d;", id);
    char* errmsg = 0;
    // 执行删除操作
    int rc = sqlite3_exec(db, sql, 0, 0, &errmsg);
    if (rc != SQLITE_OK)
    {
        printf("delete error: %s\n", errmsg); // 删除失败打印错误信息
        sqlite3_free(errmsg);
        return -1;
    }
    printf("成功删除");
    sqlite3_close(db);
    return 0;
}
// 修改图书信息（传入图书ID,不想改的信息直接回车跳过即可）
int update_bookdata(const int id)
{
    if(sqlite3_open("book.db", &db) != SQLITE_OK)
    {
        perror("打开数据库失败\n");
        exit(-1);
    }

    // 查询当前信息
    char sql[256];
    snprintf(sql, sizeof(sql), "select name, author, publishing_house, price, number, borrowing_status from bookinfo where id=%d;", id);
    sqlite3_stmt *stmt;
    if (sqlite3_prepare_v2(db, sql, -1, &stmt, NULL) != SQLITE_OK) 
    {
        printf("查询图书信息失败\n");
        sqlite3_close(db);
        return -1;
    }

    char bookname[LEN] = {0}, author[LEN] = {0}, publishing_house[LEN] = {0};
    double price = 0.0;
    int number = 0;
    int borrowing_status = 1;

    if (sqlite3_step(stmt) == SQLITE_ROW) 
    {
        strncpy(bookname, (const char*)sqlite3_column_text(stmt, 0), LEN-1);
        strncpy(author, (const char*)sqlite3_column_text(stmt, 1), LEN-1);
        strncpy(publishing_house, (const char*)sqlite3_column_text(stmt, 2), LEN-1);
        price = sqlite3_column_double(stmt, 3);
        number = sqlite3_column_int(stmt, 4);
        borrowing_status = sqlite3_column_int(stmt, 5);
    } 
    else 
    {
        printf("未找到ID为%d的图书\n", id);
        sqlite3_finalize(stmt);
        sqlite3_close(db);
        return -1;
    }
    sqlite3_finalize(stmt);

    char input[LEN];

    printf("当前图书名称：%s\n请输入新名称(直接回车保留原值)：", bookname);
    fgets(input, LEN, stdin);
    if (input[0] != '\n') 
    {
        input[strcspn(input, "\n")] = '\0';
        strncpy(bookname, input, LEN-1);
    }

    printf("当前作者：%s\n请输入新作者(直接回车保留原值)：", author);
    fgets(input, LEN, stdin);
    if (input[0] != '\n') 
    {
        input[strcspn(input, "\n")] = '\0';
        strncpy(author, input, LEN-1);
    }

    printf("当前出版社：%s\n请输入新出版社(直接回车保留原值)：", publishing_house);
    fgets(input, LEN, stdin);
    if (input[0] != '\n') 
    {
        input[strcspn(input, "\n")] = '\0';
        strncpy(publishing_house, input, LEN-1);
    }

    printf("当前价格：%.2f\n请输入新价格(直接回车保留原值)：", price);
    fgets(input, LEN, stdin);
    if (input[0] != '\n') 
    {
        double tmp;
        if (sscanf(input, "%lf", &tmp) == 1) price = tmp;
    }

    printf("当前数量：%d\n请输入新数量(直接回车保留原值)：", number);
    fgets(input, LEN, stdin);
    if (input[0] != '\n') 
    {
        int tmp;
        if (sscanf(input, "%d", &tmp) == 1) number = tmp;
    }

    printf("当前借阅状态：%d（1=可借阅，0=不可借阅）\n请输入新借阅状态(直接回车保留原值)：", borrowing_status);
    fgets(input, LEN, stdin);
    if (input[0] != '\n') 
    {
        int tmp;
        if (sscanf(input, "%d", &tmp) == 1 && (tmp == 0 || tmp == 1)) borrowing_status = tmp;
    }
    fflush(stdin);

    snprintf(sql, sizeof(sql),
        "update bookinfo set name='%s', author='%s', publishing_house='%s', price=%f, number=%d, borrowing_status=%d where id=%d;",
        bookname, author, publishing_house, price, number, borrowing_status, id);

    char* errmsg = NULL;
    int rc = sqlite3_exec(db, sql, NULL, 0, &errmsg);
    if (rc != SQLITE_OK) {
        printf("更新失败: %s\n", errmsg);
        sqlite3_free(errmsg);
        sqlite3_close(db);
        return -1;
    }
    printf("图书信息更新成功！\n");
    sqlite3_close(db);
    return 0;
}
